﻿
using System;
using System.Linq;
using System.IO;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Diagnostics;
using System.Data;
using Helena.Areas.Ventas.Models;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Helena.Areas.Configuraciones.Models;
using Helena.Areas.Productos.Models;
using Helena.Areas.Clientes.Models;
using Helena.Areas.Vendedores.Models;
using Helena.Areas.Reportes.Models;



namespace Helena.Models
{

    /// <summary>
    /// Descripción breve de Util
    /// </summary>
    /// 
    public class Fecha
    {
        public IList<year> anho { get; set; }
        public IList<Month> mes { get; set; }
    }

    public class year
    {
        public int ID { get; set; }
        public int Descripcion { get; set; }
    }

    public class Month
    {
        public int ID { get; set; }
        public string  Descripcion { get; set; }

        public Month(int i,string valor)
        {
            ID = i;
            Descripcion = valor;
        }
    }

    public class Util
    {
        static LogicaConfiguraciones conf = new LogicaConfiguraciones();
        static LogicaVenta vnt = new LogicaVenta();
        static LogicaProducto prod = new LogicaProducto();
        static LogicaCliente clt = new LogicaCliente();
        static LogicaVendedor vnd = new LogicaVendedor();

        public static string pathPdf = @"C:\Users\Pedro\Documents\Visual Studio 2010\Projects\Helena\Reportes\";
        public static string pathExcel = @"C:\Users\Pedro\Documents\Visual Studio 2010\Projects\Helena\Reportes\";
        public static string pathWord = @"C:\Users\Pedro\Documents\Visual Studio 2010\Projects\Helena\Reportes\";


        //Función que exporta a Excel
        public static void ExportarExcel(DataTable tabladatos, string direccion)
        {
            try
            {
                Document doc = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);
                string filename = direccion;

                FileStream file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

                PdfWriter.GetInstance(doc, file);
                doc.Open();
                GenerarDocumento(doc, tabladatos);
                doc.Close();
                Process.Start(filename);
            }
            catch (Exception ex)
            {

            }
        }

        //Función que genera el documento Pdf
        public static void GenerarDocumento(Document document, DataTable tabladatos)
        {
            //se crea un objeto PdfTable con el numero de columnas del
            //dataGridView
            PdfPTable datatable = new PdfPTable(tabladatos.Columns.Count);
            //asignamos algunas propiedades para el diseño del pdf
            datatable.DefaultCell.Padding = 3;
            float[] headerwidths = GetTamañoColumnas(tabladatos);
            datatable.SetWidths(headerwidths);
            datatable.WidthPercentage = 100;
            datatable.DefaultCell.BorderWidth = 2;
            datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

            //SE GENERA EL ENCABEZADO DE LA TABLA EN EL PDF
            for (int i = 0; i < tabladatos.Columns.Count; i++)
            {
                datatable.AddCell(tabladatos.Columns[i].ColumnName);
            }

            datatable.HeaderRows = 1;
            datatable.DefaultCell.BorderWidth = 1;

            //SE GENERA EL CUERPO DEL PDF
            foreach (DataRow row in tabladatos.Rows)
            {
                for (int j = 0; j < tabladatos.Columns.Count; j++)
                {
                    datatable.AddCell(row[j].ToString());
                }
            }

            //for (int i = 0; i < tabladatos.Rows.Count; i++)
            //{
            //    for (int j = 0; j < tabladatos.Columns.Count; j++)
            //    {
            //        datatable.AddCell(tabladatos.c[j][i].Value.ToString());
            //    }
            //    datatable.CompleteRow();
            //}

            //SE AGREGAR LA PDFPTABLE AL DOCUMENTO
            document.Add(datatable);
        }

        //Función que obtiene los tamaños de las columnas del grid
        public static float[] GetTamañoColumnas(DataTable dt)
        {
            float[] values = new float[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                values[i] = (float)dt.Columns[i].ColumnName.Length;
            }
            return values;
        }

        public static void GuardarLog(string Name, string Log)
        {
            string fileName = Name;
            StreamWriter writer = File.CreateText(fileName);
            writer.Write(Log);
            writer.Close();
        }

        public static string CrearTablaSalida(String[] cabecera, String[] Cuerpo)
        {
            StringBuilder HtmlStr = new StringBuilder("");
            string str;

            //Cabeceras

            str = "<table style='width:80%'>" +
                    "<tr>";
            foreach (string s in cabecera)
            {
                str += "<td style='background-color: #0000FF; font-family: Arial, Helvetica, sans-serif; font-size: medium; font-weight: bold; font-style: normal; border-style: inset; padding: 2px; margin: 2px; color: #CCFF33;'>" + s + "</td>";
            };
            str += "</tr>";


            //cuerpo

            int contadorcabecera = cabecera.Count();
            int contador = 0;
            foreach (string s in Cuerpo)
            {
                if (contador == 0)
                {
                    str += "<tr>";
                }

                if (contador == contadorcabecera)
                {
                    contador = 0;
                    str += "</tr>";
                }

                str += "<td style='border-style: solid; border-width: 1px 0px 1px 0px; border-color: #808080; background-color: #FFFFFF; font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-weight: normal; text-transform: capitalize; color: #3366CC; '>" + s + "</td>";
                contador++;
            }

            str += "</table>";
            return str;
        }

        public static string PiedeCorreo()
        {
            string salida = string.Empty;
            salida = "<table style='width:50%'>" +
                        "<tr>" +
                            "<td>" + "<b>Envio Automatico</b>" + "</td>" +
                            "<td>" + "<b>Inteligencia de Negocios</b>" + "</td>" +
                        "</tr>" +
                        "<tr>" +
                            "<td>" + "<b>Creado por </b>" + "</td>" +
                            "<td>" + "pedro.curich@telefonica.com" + "</td>" +
                        "</tr>" +
                        "<tr>" +
                            "<td>" + "<b>Administrado por </b>" + "</td>" +
                            "<td>" + "andrea.salinas@telefonica.com" + "</td>" +
                        "</tr>" +
                    "</table>";
            return salida;
        }

        public static void ImprimirVenta(VentaView v)
        {
            string Cadena = String.Empty;
            List<DetalleVentaView> dvw = vnt.DetallesDeUnaVenta(v.ID);
            LocalView l = conf.ObtenerLocal();

            Cadena = "          " + l.NombreLocal + "\n" +
                     l.Direccion.Substring(0,34) + "\n" +
                     "" + l.Direccion.Substring(33) + "\n" +
                     "SANTIAGO DE SURCO - LIMA - LIMA" + "\n" +
                     "RUC:" + l.Ruc + "  Serie # FFFG159F02" + "\n\n";
            if ((v.Ticket > 0)&&(v.Boleta==0)&&(v.Factura==0))
            {
                string ticket = v.Ticket.ToString();
                if(v.Ticket<10) {ticket="001-0000000"+ticket;}               
                if((v.Ticket>=10)&&(v.Ticket<100)) {ticket="001-000000"+ticket;}
                if((v.Ticket>=100)&&(v.Ticket<1000)) {ticket="001-00000"+ticket;}
                if((v.Ticket>=1000)&&(v.Ticket<10000)) {ticket="001-0000"+ticket;}
                if((v.Ticket>=10000)&&(v.Ticket<100000)) {ticket="001-000"+ticket;}
                if((v.Ticket>=100000)&&(v.Ticket<1000000)) {ticket="001-00"+ticket;}
                if((v.Ticket>=1000000)&&(v.Ticket<10000000)) {ticket="001-0"+ticket;}
                Cadena += "Ticket: # " +ticket + "\n";            
            }

            if ((v.Ticket == 0) && (v.Boleta >0) && (v.Factura == 0))
            {
                Cadena += "Boleta: " + v.Boleta + "\n" ;
            }

            if ((v.Ticket == 0) && (v.Boleta == 0) && (v.Factura > 0))
            {
                string Factura = v.Factura.ToString();
                if(v.Ticket<10) {Factura="001-0000000"+Factura;}               
                if((v.Ticket>=10)&&(v.Ticket<100)) {Factura="001-000000"+Factura;}
                if((v.Ticket>=100)&&(v.Ticket<1000)) {Factura="001-00000"+Factura;}
                if((v.Ticket>=1000)&&(v.Ticket<10000)) {Factura="001-0000"+Factura;}
                if((v.Ticket>=10000)&&(v.Ticket<100000)) {Factura="001-000"+Factura;}
                if((v.Ticket>=100000)&&(v.Ticket<1000000)) {Factura="001-00"+Factura;}
                if((v.Ticket>=1000000)&&(v.Ticket<10000000)) {Factura="001-0"+Factura;}
                Cadena += "Factura: # " +Factura + "\n";            
            }

            Cadena +="Fecha :" + DateTime.Now + "\n" +
                     "Vendedor (a) :" + vnd.cabecera() + "\n" +
                     "\n" +
                     "----------------------------------------" +
                     "           Ticket - Factura             " +
                     "----------------------------------------\n" +
                     "Descripcion" + "\n" +
                     "               Cant.   P.U.    Total     " +
                     "----------------------------------------";
            foreach (DetalleVentaView d in dvw)
            {
                Cadena += prod.i_RetornarProducto(d.ProductoID).Descripcion + "\n" +
                     "            " + d.Cantidad + "       " + d.PrecioU + "         " + d.Subtotal + "\n";
            }

            Cadena += "----------------------------------------" +"\n" +
                   "Sub - Total : S/. " + v.Sub_Total + "\n" +
                   "IGV         : S/. " + Math.Round(v.Valor_Del_Igv_En_Soles,2).ToString() + "\n" +
                   "Dscto       : S/. " + Convert.ToDouble(v.Descuento).ToString() + " %\n" +
                   "V.Venta     : S/. " + Convert.ToDouble(v.Total_En_Soles).ToString() + "\n" +
                   "----------------------------------------" +"\n" +
                   "Efectivo    : S/. " + Convert.ToDouble(v.Pago_en_Efectivo_en_Soles).ToString() + "\n" +
                   "Dolares     : $/. " + Convert.ToDouble(v.Pago_en_Efectivo_en_Dolares).ToString() + "   T.C. : S/. " + v.ValorTipoCambio + "\n" +
                   "Tarjeta     : S/. " + Convert.ToDouble(v.Pago_con_Tarjeta_en_Soles).ToString() + "\n" +
                   "Vuelto      : S/. " + Convert.ToDouble(v.Vuelto).ToString() + "\n" +
                   "----------------------------------------" + "\n\n\n" +
                   "RUC o DNI    :" + clt.i_RetornarCliente(v.ClienteID).Ruc_Dni + "    " + "\n" +
                   "Razon Social :" + clt.i_RetornarCliente(v.ClienteID).RazonSocial + "    " + "\n" +
                   "Direccion    :" + clt.i_RetornarCliente(v.ClienteID).Direccion + "    " + "\n" +
                   "Por ser Productos Perecibles \n" +
                   "No se aceptan cambios ni devoluciones\n\n\n\n\n\n\n\n\n\n";

            RawPrinterHelper rph = new RawPrinterHelper();
            rph.SendStringToPrinter(@"\\HELENA2-PC\EPSON TM-U220 Receipt", Cadena);
            rph.SendStringToPrinter(@"\\HELENA2-PC\EPSON TM-U220 Receipt", "\x1B" + "m");// caracteres de corte
            rph.SendStringToPrinter(@"\\HELENA2-PC\EPSON TM-U220 Receipt", "\x1B" + "d" + "\x09"); // avanza 9 renglones

        }

        public static void ImprimirCierreCaja(string Cadena)
        {
            RawPrinterHelper rph = new RawPrinterHelper();
            rph.SendStringToPrinter(@"\\HELENA2-PC\EPSON TM-U220 Receipt", Cadena);
        }


    }
}



public class RawPrinterHelper
{
    // Structure and API declarions:
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDataType;
    }
    [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

    // SendBytesToPrinter()
    // When the function is given a printer name and an unmanaged array
    // of bytes, the function sends those bytes to the print queue.
    // Returns true on success, false on failure.
    public bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false; // Assume failure unless you specifically succeed.

        di.pDocName = "My C#.NET RAW Document";
        di.pDataType = "RAW";
        //di.

        // Open the printer.
        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            // Start a document.
            if (StartDocPrinter(hPrinter, 1, di))
            {
                // Start a page.
                if (StartPagePrinter(hPrinter))
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if (bSuccess == false)
        {
            dwError = Marshal.GetLastWin32Error();
            using (StreamWriter sw = new StreamWriter(@"C:\reportes\TestFile.txt",true))
            {
                sw.WriteLine(dwError +" - "+ DateTime.Now.ToString());
                sw.WriteLine("-------------------");
            }
        }
        return bSuccess;
    }



    public bool SendFileToPrinter(string szPrinterName, string szFileName)
    {
        // Open the file.
        FileStream fs = new FileStream(szFileName, FileMode.Open);
        // Create a BinaryReader on the file.
        BinaryReader br = new BinaryReader(fs);
        // Dim an array of bytes big enough to hold the file's contents.
        Byte[] bytes = new Byte[fs.Length];
        bool bSuccess = false;
        // Your unmanaged pointer.
        IntPtr pUnmanagedBytes = new IntPtr(0);
        int nLength;

        nLength = Convert.ToInt32(fs.Length);
        // Read the contents of the file into the array.
        bytes = br.ReadBytes(nLength);
        // Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
        // Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
        // Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
        // Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes);
        return bSuccess;
    }
    public bool SendStringToPrinter(string szPrinterName, string szString)
    {
        IntPtr pBytes;
        Int32 dwCount;
        // How many characters are in the string?
        dwCount = szString.Length;
        // Assume that the printer is expecting ANSI text, and then convert
        // the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString);
        // Send the converted ANSI string to the printer.
        SendBytesToPrinter(szPrinterName, pBytes, dwCount);
        Marshal.FreeCoTaskMem(pBytes);
        return true;
    }
}